package com.scy.weibotest01.controller;

import com.scy.weibotest01.mapper.UserMapper;
import com.scy.weibotest01.pojo.dto.UserLoginDTO;
import com.scy.weibotest01.pojo.dto.UserRegDTO;
import com.scy.weibotest01.pojo.entity.User;
import com.scy.weibotest01.pojo.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.Date;

@RestController
public class UserController {
    @Autowired(required = false)
    UserMapper mapper;

    @RequestMapping("/reg")
    public int reg(@RequestBody UserRegDTO userRegDTO){
        System.out.println("userDTO = " + userRegDTO);
//        这里只是查询
        UserVO user = mapper.selectByUsername(userRegDTO.getUsername());
        if (user!=null){
            return 2;
        }
        User u = new User();
        BeanUtils.copyProperties(userRegDTO,u);
        u.setCreated(new Date());
        mapper.insert(u);
        return 1;
    }
    @RequestMapping("/login")
    public int login(@RequestBody UserLoginDTO userLoginDTO, HttpSession session){
        System.out.println("userLoginDTO = " + userLoginDTO);
        UserVO userVO = mapper.selectByUsername(userLoginDTO.getUsername());
        if (userVO != null){
            if (userVO.getPassword().equals(userLoginDTO.getPassword())){
                session.setAttribute("user",userVO);
                return 1;
            }
            return 2;
        }
        return 3;
    }
    @RequestMapping("/currentUser")
    public UserVO currentUser(HttpSession session){
        UserVO user = (UserVO) session.getAttribute("user");
        System.out.println(user);
        return user;
    }
    @RequestMapping("/logout")
    public void logout(HttpSession session){
        session.removeAttribute("user");
    }
}
